#!/usr/bin/env python3
"""
在服务器上运行此脚本以验证数据库连接配置
"""

import os
import sys
from sqlalchemy import create_engine, text

def check_database_connection():
    """检查数据库连接"""
    # 使用应用中的配置
    database_url = 'mysql+pymysql://root:!Dd930308@3o13.com/svt_backend'
    
    print("检查数据库连接...")
    print(f"连接URL: {database_url}")
    
    try:
        engine = create_engine(database_url, echo=True, connect_args={"connect_timeout": 10})
        with engine.connect() as connection:
            # 测试基本连接
            result = connection.execute(text("SELECT 1"))
            print("✓ 基本连接测试成功")
            
            # 检查数据库版本
            result = connection.execute(text("SELECT VERSION()"))
            version = result.fetchone()
            print(f"✓ MySQL版本: {version[0]}")
            
            # 检查数据库是否存在
            result = connection.execute(text("SHOW DATABASES LIKE 'svt_backend'"))
            if result.fetchone():
                print("✓ 数据库 'svt_backend' 存在")
            else:
                print("⚠ 数据库 'svt_backend' 不存在")
            
            # 检查表是否存在
            try:
                result = connection.execute(text("SHOW TABLES FROM svt_backend LIKE 'access_logs'"))
                if result.fetchone():
                    print("✓ 表 'access_logs' 存在")
                else:
                    print("ℹ 表 'access_logs' 不存在（将在初始化时创建）")
            except Exception as e:
                print(f"ℹ 无法检查表: {e}")
                
            return True
            
    except Exception as e:
        print(f"✗ 数据库连接失败: {e}")
        return False

if __name__ == '__main__':
    success = check_database_connection()
    if success:
        print("\n🎉 数据库连接配置正确!")
        sys.exit(0)
    else:
        print("\n❌ 数据库连接配置存在问题，请检查配置。")
        sys.exit(1)